package org.alwayssuper.web.endpoint;

import lombok.extern.slf4j.Slf4j;
import org.alwayssuper.netmc.core.HandlerInterceptor;
import org.alwayssuper.netmc.session.Session;
import org.alwayssuper.protocol.basics.GBTMessage;
import org.alwayssuper.protocol.commons.GBTRequestType;
import org.alwayssuper.protocol.commons.GBTResponseType;
import org.alwayssuper.protocol.gbt32960.CommonResponse;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author alwaysSuper
 */
@Slf4j
@Component
public class GBTHandlerInterceptor implements HandlerInterceptor<GBTMessage> {

    // 用于延迟断开连接的线程池
    private final ScheduledExecutorService disconnectScheduler = Executors.newScheduledThreadPool(2);

    /** 未找到对应的Handle */
    @Override
    public GBTMessage notSupported(GBTMessage request, Session session) {
        GBTMessage response = null;
        if(request.getResponseType() == GBTResponseType.命令){
            response = responseMessage(request, GBTResponseType.其他错误);
        }
        log.info("{}\n<<<<-未识别的消息{}\n>>>>-{}", session, request, response);
        return response;
    }

    /** 调用之前 */
    @Override
    public boolean beforeHandle(GBTMessage request, Session session) {
        int messageId = request.getMessageId();
        // 车辆登入和平台登入消息无需验证注册状态
        if (messageId == GBTRequestType.车辆登入 || messageId == GBTRequestType.平台登入) {
            return true;
        }
        // 其他消息需要验证设备是否已注册
        if (!session.isRegistered()) {
            log.warn("{}未注册的设备<<<<-{}", session, request);
            return false;
        }
        // 🔥 修复错误：已注册设备应该允许处理，返回true
        return true;
    }

    /** 调用之后，返回值为void的 */
    @Override
    public GBTMessage successful(GBTMessage request, Session session) {
        GBTMessage response = null;
        if(request.getResponseType() == GBTResponseType.命令) {
            response = responseMessage(request, GBTResponseType.成功);
            
            // 对于车辆登出消息，为保证下行消息发送，延迟断开连接
            if (request.getMessageId() == GBTRequestType.车辆登出) {
                log.info("{}车辆登出消息，将在100ms后断开连接", session);
                disconnectScheduler.schedule(() -> {
                    try {
                        session.invalidate();
                        log.info("{}车辆登出延迟断开连接成功", session);
                    } catch (Exception e) {
                        log.error("{}车辆登出断开连接异常", session, e);
                    }
                }, 100, TimeUnit.MILLISECONDS);
            }
        }
        return response;
    }

    /** 调用之后 */
    @Override
    public void afterHandle(GBTMessage request, GBTMessage response, Session session) {

    }

    /** 调用之后抛出异常的 */
    @Override
    public GBTMessage exceptional(GBTMessage request, Session session, Throwable e) {
        GBTMessage response = null;
        if(request.getResponseType() == GBTResponseType.命令){
            response = responseMessage(request, GBTResponseType.其他错误);
        }
        log.warn(session + "\n<<<<-" + request + "\n>>>>-" + response + '\n', e);
        return response;
    }

    private GBTMessage responseMessage(GBTMessage request, Integer responseType){
        // 使用专门的通用响应消息类，避免类型不匹配问题
        CommonResponse response = new CommonResponse();
        response.copyBy(request);
        response.setResponseType(responseType);
        response.setSendTime(LocalDateTime.now());

        return response;
    }
}
